<script setup>
import { ref, watch, inject, provide, onMounted, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useConfigStore } from '@/stores/config'
import { useRouter } from 'vue-router'
import userApi from '@/apis/user'

import Profile from '@/components/user/Profile.vue'
import UploadAvatar from '@/components/user/UploadAvatar.vue'

const route = useRouter()
const authStore = useAuthStore()
const configStore = useConfigStore()

const user = ref(authStore.user)
const logout = inject('logout')
const bindEmail = computed(() => configStore.get('user.email_feature', []).includes('bind'))
const bindMobile = computed(() => configStore.get('user.mobile_feature', []).includes('bind'))

const reloadUserInfo = async () => {
  const { data } = await userApi.profile.info()
  user.value = data
}

onMounted(async () => {
  await reloadUserInfo()
})

watch(user, (newVal) => authStore.setUser(newVal), { deep: true })

provide('reloadUserInfo', reloadUserInfo)
</script>

<template>
  <div
    class="flex flex-col w-full min-h-80 lg:border lg:border-[--el-border-color] lg:mt-5 lg:max-w-[780px] lg:mx-auto lg:shadow-sm lg:rounded"
  >
    <!-- 个人信息卡片框，背景渐变色-->
    <div class="flex items-center w-full px-5 py-5 bg-[--el-fill-color-light] rounded">
      <UploadAvatar @success="(url) => (user.avatar = url)">
        <div class="avatar">
          <el-avatar :size="80" :src="user.avatar" @error="() => true" />
          <div class="change">更换</div>
        </div>
      </UploadAvatar>
      <div class="flex-1 ml-2 mr-12 space-y-1">
        <div class="flex items-center">
          <span class="text-xl font-bold">{{ user.nickname || '未设置昵称' }}</span>
        </div>
        <div class="text-sm space-x-1">
          <el-tag size="small" type="warning" v-if="user.vip">vip</el-tag>
          <el-tag size="small" type="success">{{ user.score }} 积分</el-tag>
        </div>
        <div class="text-sm text-gray-500">
          {{ user.mobile }}
        </div>
      </div>
      <div class="hidden sm:block">
        <el-button size="small" type="primary" plain @click="logout">
          <FontAwesomeIcon icon="sign-out-alt" />
          <span class="pl-1">登出</span>
        </el-button>
      </div>
    </div>
    <div class="mt-2 px-5">
      <Profile v-model="user" :bindEmail :bindMobile />
    </div>
  </div>
</template>

<style scoped>
.avatar {
  @apply relative w-20 h-20 rounded-full mr-3 shadow
  overflow-hidden cursor-pointer;
}

.change {
  @apply absolute bottom-0 left-0 w-full bg-[--el-fill-color-light] sm:opacity-0 
  bg-black bg-opacity-30 text-gray-100 text-center text-sm py-1;
}
.avatar:hover .change {
  opacity: 1;
}
</style>
